package com.SmartCampus.system.controller;

import com.SmartCampus.system.annotation.AuthCheck;
import com.SmartCampus.system.common.BaseResponse;
import com.SmartCampus.system.common.DeleteRequest;
import com.SmartCampus.system.common.ErrorCode;
import com.SmartCampus.system.common.ResultUtils;
import com.SmartCampus.system.constant.UserConstant;
import com.SmartCampus.system.exception.BusinessException;
import com.SmartCampus.system.exception.ThrowUtils;
import com.SmartCampus.system.model.dto.announcement.AnnouncementAddRequest;
import com.SmartCampus.system.model.dto.announcement.AnnouncementQueryRequest;
import com.SmartCampus.system.model.dto.announcement.AnnouncementUpdateRequest;
import com.SmartCampus.system.model.entity.Announcement;
import com.SmartCampus.system.service.AnnouncementService;
import com.SmartCampus.system.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * 通知接口
 *
 * @author wangliang
 */
@RestController
@RequestMapping("/announcement")
@Slf4j
@Api(tags = "通知接口")
public class AnnouncementController {

    @Resource
    private AnnouncementService announcementService;

    @Resource
    private UserService userService;

    // region 增删改查

    /**
     * 创建通知
     *
     * @param announcementAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    @ApiOperation(value = "创建通知")
    public BaseResponse<Long> addAnnouncement(@RequestBody AnnouncementAddRequest announcementAddRequest, HttpServletRequest request) {
        if (announcementAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String username = userService.getLoginUser(request).getUsername();
        Announcement announcement = new Announcement();
        BeanUtils.copyProperties(announcementAddRequest, announcement);
        announcement.setAuthor(username);
        announcement.setPublishDate(new Date());
        boolean result = announcementService.save(announcement);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(announcement.getId());
    }

    /**
     * 删除通知（仅管理员）
     *
     * @param deleteRequest
     * @return
     */
    @PostMapping("/delete")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @ApiOperation(value = "删除通知（仅管理员）")
    public BaseResponse<Boolean> deleteUser(@RequestBody DeleteRequest deleteRequest) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "id 不能为空");
        }
        boolean result = announcementService.removeById(deleteRequest.getId());
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(result);
    }

    /**
     * 更新通知
     *
     * @param announcementUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @ApiOperation(value = "更新通知")
    public BaseResponse<Boolean> updateUser(@RequestBody AnnouncementUpdateRequest announcementUpdateRequest, HttpServletRequest request) {
        if (announcementUpdateRequest.getId() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "id 不能小于等于0");
        }
        String username = userService.getLoginUser(request).getUsername();
        QueryWrapper<Announcement> oldAnnouncement = new QueryWrapper<>();
        oldAnnouncement.eq("id", announcementUpdateRequest.getId());
        Announcement announcement = announcementService.getOne(oldAnnouncement);
        if (announcement == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        if (!username.equals(announcement.getAuthor()) && !userService.getLoginUser(request).getUserRole().equals(UserConstant.ADMIN_ROLE)) {
            throw new BusinessException(ErrorCode.FORBIDDEN_ERROR, "无权限更新");
        }
        if (announcementUpdateRequest.getTitle() == null || announcementUpdateRequest.getTitle().equals("")) {
            announcementUpdateRequest.setTitle(announcement.getTitle());
        }
        if (announcementUpdateRequest.getContent() == null || announcementUpdateRequest.getContent().equals("")) {
            announcementUpdateRequest.setContent(announcement.getContent());
        }
        BeanUtils.copyProperties(announcementUpdateRequest, announcement);
        boolean result = announcementService.updateById(announcement);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(result);
    }

    /**
     * 分页获取通知列表（所有人）
     *
     * @param announcementQueryRequest
     * @return
     */
    @PostMapping("/get/all")
    @ApiOperation(value = "分页获取通知列表（所有人）")
    public BaseResponse<Page<Announcement>> getAnnouncementByAll(@RequestBody AnnouncementQueryRequest announcementQueryRequest) {
        long current = announcementQueryRequest.getCurrent() == 0 ? 1 : announcementQueryRequest.getCurrent();
        long size = announcementQueryRequest.getPageSize() == 0 ? 10 : announcementQueryRequest.getPageSize();
        Page<Announcement> page = new Page<>(current, size);
        Page<Announcement> announcementPage = announcementService.getAnnouncementByAll(page, announcementQueryRequest);
        if (announcementPage == null) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "查询失败，请联系管理员");
        }
        return ResultUtils.success(announcementPage);
    }

    /**
     * 分页获取用户发布的通知列表
     *
     * @param announcementQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/get/my")
    @ApiOperation(value = "分页获取用户发布的通知列表")
    public BaseResponse<Page<Announcement>> getAnnouncementByMy(@RequestBody AnnouncementQueryRequest announcementQueryRequest, HttpServletRequest request) {
        if (announcementQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String username = userService.getLoginUser(request).getUsername();
        long current = announcementQueryRequest.getCurrent() == 0 ? 1 : announcementQueryRequest.getCurrent();
        long size = announcementQueryRequest.getPageSize() == 0 ? 10 : announcementQueryRequest.getPageSize();

        Page<Announcement> page = new Page<>(current, size);
        Page<Announcement> announcementPage = announcementService.getAnnouncementByMy(page, announcementQueryRequest, username);
        if (announcementPage == null) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "查询失败，请联系管理员");
        }
        return ResultUtils.success(announcementPage);
    }

    // endregion
}
